/*
 * Copyright (C) 2022-2024 Huawei Device Co., Ltd.
 * Licensed under the MIT License, (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { AbstractPubSubSupport } from './AbstractPubSubSupport'
import type { IBusConfiguration } from '../config/IBusConfiguration'
import type { IPublicationErrorHandler } from './error/IPublicationErrorHandler'
import ArrayList from '@ohos.util.ArrayList';
import { ConsoleLogger } from './error/ConsoleLogger'
import { PublicationError } from './error/PublicationError'

export class AbstractSyncAsyncMessageBus<T> extends AbstractPubSubSupport<T> {
    private errorHandlers: ArrayList<IPublicationErrorHandler> = new ArrayList<IPublicationErrorHandler>();

    constructor(config: IBusConfiguration) {
        super(config);
        let arrayErrorHandlers: Array<IPublicationErrorHandler> = config.getRegisteredPublicationErrorHandlers();
        if (!arrayErrorHandlers && arrayErrorHandlers.length > 0) {
            arrayErrorHandlers.forEach((value) => {
                this.setErrorHandle(value);
            })
        }
        if (this.isErrorHandleEmpty()) {
            this.errorHandlers.add(new ConsoleLogger());
        }
    }

    setErrorHandle(error: IPublicationErrorHandler) {
        try{
            if (!this.errorHandlers.has(error)) {
                this.errorHandlers.add(error);
            }
        }catch(e){
            console.log(e);
        }
    }

    isErrorHandleEmpty(): boolean {
        try{
            return this.errorHandlers.isEmpty();
        }catch(e){
            console.log(e);
        }
        return false;
    }

    handlePublicationError(error: PublicationError) {
        try{
            this.errorHandlers.forEach((value) => {
                value.handleError(error);
            })
        }catch(e){
            console.log(e);
        }
    }
}